package com.suncky.frame.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;

public class KeyboardUtil {

	/**
	 * 如果输入法在窗口上已经显示，则隐藏，反之则显示
	 */
	public static void toggleInputMethod(Context context) {
		InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 显示键盘
	 * @param activity
	 * @param v
	 */
	public static void showInputMethod(Activity activity, View v) {
		InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (activity.getCurrentFocus() != null) {
			imm.showSoftInput(v,
					InputMethodManager.RESULT_UNCHANGED_SHOWN);
		}
	}

	/**
	 * 隐藏键盘
	 * @param activity
	 */
	public static void dismissInputMethod(Activity activity) {
		InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (activity.getCurrentFocus() != null) {
			if (imm.isActive()) {
				imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
	}

	public static void setKeyboardListener(Activity activity, KeyboardChangeListener listener) {
		//获取activity的根视图
		View rootView = activity.getWindow().getDecorView();
		//监听视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变
		rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
			boolean isShowed = false;//键盘是否弹出

			@Override
			public void onGlobalLayout() {
				int rootViewHeight = rootView.getHeight();//纪录根视图的显示高度
				//获取当前根视图在屏幕上显示的大小
				Rect r = new Rect();
				rootView.getWindowVisibleDisplayFrame(r);
				int visibleHeight = r.height();

				//可见高度小于3/4，可以看作软键盘显示了
				if (rootViewHeight - visibleHeight > rootViewHeight / 4) {
					if (listener != null && !isShowed) {
						listener.onShow();
					}
					isShowed = true;
				} else{
					if (listener != null && isShowed) {
						listener.onHide();
					}
					isShowed = false;
				}

			}
		});
	}

	public interface KeyboardChangeListener{
		void onShow();
		void onHide();

	}
}
